from google.appengine.ext import db
from django.core.exceptions import SuspiciousOperation
from django.contrib.sessions.backends.base import SessionBase


class Session(db.Model):
    session_key = db.StringProperty()
    session_data = db.TextProperty()
    expire_date = db.DateTimeProperty()


class SessionStore(SessionBase):
    """
    Implements a Google DataStore session store.
    """
    def __init__(self, session_key=None):
        super(SessionStore, self).__init__(session_key)


    def _get_session(self, session_key=None):
        if session_key is None:
            session_key = self.session_key
        return Session.all().filter('session_key =', session_key).get()


    def load(self):
        session = self._get_session()
        try:
            session_data = self.decode(session.session_data)
        except SuspiciousOperation:
            session_data = dict()
            self._session_key = self._get_new_session_key()
            self._session_cache = dict()
            self.save()
            # Ensure the user is notified via a new cookie.
            self.modified = True
        return session_data


    def save(self):
                session = self._get_session()
                if session is None:
                        session = Session(session_key=self.session_key)
                session.session_data = self.encode(self._session)
                session.put()


    def exists(self, session_key):
                return self._get_session(session_key) is not None


    def delete(self, session_key):
                self._get_session().delete()


    def clean(self):
        pass
